const Joi = require('joi');

const RoleValidator = async (ctx, next) => {

    let RoleSchema = Joi.object({
        jobTitle: Joi.string().required().trim().max(30).error(new Error('jobTitle参数填写错误')),
    });

    const bodyParams = ctx.request.body
    if (bodyParams) {
        const {error} = RoleSchema.validate(bodyParams, {
            abortEarly: true
        });
        if (error) {
            return ctx.body = {
                status: 1,
                msg: error.message
            }
        }
    } else {
        return ctx.body = {
            status: 1,
            msg: '请填写必填参数'
        }
    }

    await next()
}

const RolePermissionValidator = async (ctx, next) => {
    let RolePermissionSchema = Joi.object({
        roleId: Joi.number().required().error(new Error('roleId参数填写错误')),
        permissionId: Joi.string().trim().error(new Error('permissionId参数填写错误')),
    });

    const bodyParams = ctx.request.body
    if (bodyParams) {
        const {error} = RolePermissionSchema.validate(bodyParams, {
            abortEarly: true
        });
        if (error) {
            return ctx.body = {
                status: 1,
                msg: error.message
            }
        }
    } else {
        return ctx.body = {
            status: 1,
            msg: '请填写必填参数'
        }
    }

    await next()
}

const UserRoleValidator = async (ctx, next) => {
    let UserRoleSchema = Joi.object({
        userId: Joi.number().required().error(new Error('userId参数填写错误')),
        roleId: Joi.string().required().trim().error(new Error('roleIds参数填写错误')),
    });

    const bodyParams = ctx.request.body
    if (bodyParams) {
        const {error} = UserRoleSchema.validate(bodyParams, {
            abortEarly: true
        });
        if (error) {
            return ctx.body = {
                status: 1,
                msg: error.message
            }
        }
    } else {
        return ctx.body = {
            status: 1,
            msg: '请填写必填参数'
        }
    }

    await next()
}

module.exports = {
    RoleValidator,
    RolePermissionValidator,
    UserRoleValidator
}
